// ALIBESonar.cpp file 
#include <Arduino.h>
#include <ALIBESonar.h>
	
	
	// public
	ALIBESonar::ALIBESonar(){
	}
	long ALIBESonar::getFrontDistanceInIN(){
		return _getDistanceInIN(ALIBESONAR_FRONT_PIN);
	}
	long ALIBESonar::getFrontDistanceInCM(){
		return _getDistanceInCM(ALIBESONAR_FRONT_PIN);
	}
	long ALIBESonar::getRearDistanceInIN(){
		return _getDistanceInIN(ALIBESONAR_REAR_PIN);
	}
	long ALIBESonar::getRearDistanceInCM(){
		return _getDistanceInCM(ALIBESONAR_REAR_PIN);
	}
	
	// private
	long ALIBESonar::_getDistanceInIN(int _pin){
		  // establish variables for duration of the ping, 
		  // and the distance result in inches and centimeters:
		  long _duration;
		  _duration = _getDuration(_pin);

		  // convert the time into a distance
		  return  _microsecondsToInches(_duration);
	}
	
	long ALIBESonar::_getDistanceInCM(int _pin){
		  // establish variables for duration of the ping, 
		  // and the distance result in inches and centimeters:
		  long _duration;
		  _duration = _getDuration(_pin);

		  // convert the time into a distance
		  return _microsecondsToCentimeters(_duration);
	}

	long ALIBESonar::_getDuration(int _pin){
		pinMode(_pin, OUTPUT);

		digitalWrite(_pin, LOW);
		delayMicroseconds(2);
		
		digitalWrite(_pin, HIGH);
		delayMicroseconds(5);
		digitalWrite(_pin, LOW);

		// The same pin is used to read the signal from the PING))): a HIGH
		// pulse whose duration is the time (in microseconds) from the sending
		// of the ping to the reception of its echo off of an object.
		pinMode(_pin, INPUT);
		return pulseIn(_pin, HIGH);
	}


	long ALIBESonar::_microsecondsToInches(long _ms){
		  // According to Parallax's datasheet for the PING))), there are
		  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
		  // second).  This gives the distance travelled by the ping, outbound
		  // and return, so we divide by 2 to get the distance of the obstacle.
		  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
		  return _ms / 74 / 2;
	}

	long ALIBESonar::_microsecondsToCentimeters(long _ms){
	  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
	  // The ping travels out and back, so to find the distance of the
	  // object we take half of the distance travelled.
	  return _ms / 29 / 2;
	}	
